package manage.filter;

import entity.Admin;
import manage.shiro.AdminRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import utils.RedisTemplate;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;
import java.util.Deque;

public class ShiroLogoutFilter extends LogoutFilter {

    private Cache<String, Deque<Serializable>> cacheKickout;

    private Cache<String, Object> cacheAuthentication;

    public void setCacheManager(CacheManager cacheManager) {
        this.cacheKickout = cacheManager.getCache("shiro-kickout-session");
        this.cacheAuthentication = cacheManager.getCache("manage.shiro.AdminRealm.authenticationCache");
    }

    /**
     * 自定义登出,登出之后,清理当前用户redis部分缓存信息
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

        //登出操作 清除缓存  subject.logout() 可以自动清理缓存信息, 这些代码是可以省略的  这里只是做个笔记 表示这种方式也可以清除
        Subject subject = getSubject(request,response);
        Admin admin = (Admin) subject.getPrincipal();
        String username = admin.getUsername();
        //清除控制同时在线人数的key
        cacheKickout.remove(username);
        //清除相关权限
        cacheAuthentication.remove(username);
        //登出
        subject.logout();

        //获取登出后重定向到的地址
        String redirectUrl = getRedirectUrl(request,response,subject);
        //重定向
        issueRedirect(request,response,redirectUrl);
        return false;
    }

}
